import { Button, Form, Input, InputNumber, message, Modal, Space, TimePicker } from 'antd';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import * as moment from 'moment';
import styles from '../index.less';
import type { ChargeRuleItem } from '../data';
import { addNewRules } from '../service';

interface RuleItem {
  duration: moment.Moment[];
  maxPrice: number;
  price: {
    value: number;
    unit: number;
  };
}

const handleTimeMoment = (time?: number) => moment.unix(time !== undefined ? (time - 480) * 60 : 0);
const translateTimeToMin = (time: moment.Moment) => {
  const temp = time || moment();
  return temp.hour() * 60 + temp.minute();
};

interface SecondStepProp {
  currRules: ChargeRuleItem[];
  setUnvisible: () => void;
  visible: boolean;
  ruleId: string;
}

export default (props: SecondStepProp) => {
  const { currRules, visible, setUnvisible, ruleId } = props;
  const [form] = Form.useForm();
  // 此处添加项
  const initialRules = currRules.map((item) => ({
    maxPrice: item.maxPrice ? item.maxPrice / 100 : null,
    price: {
      value: item.pricing ? item.pricing / 100 : null,
      unit: item.priceUnit ? Number((item.priceUnit / 60).toFixed(1)) : item.priceUnit,
    },
    duration: [handleTimeMoment(item.startTime), handleTimeMoment(item.endTime)],
  }));
  return (
    <Modal
      title="配置规则时间段"
      width="60vw"
      destroyOnClose
      visible={visible}
      centered
      className={styles.addbillmodal}
      okText="更新配置"
      cancelText="取消"
      onCancel={() => setUnvisible()}
      onOk={async () => {
        try {
          const values = await form.validateFields();
          const rules: ChargeRuleItem[] = values.rules.map((item: RuleItem) => ({
            maxPrice: item.maxPrice * 100,
            priceUnit: item.price.unit * 60,
            pricing: item.price.value * 100,
            schemeId: ruleId,
            startTime: translateTimeToMin(item.duration[0]),
            endTime: translateTimeToMin(item.duration[1]) || 1440,
          }));
          const starttimes = rules.map((item) => item.startTime).sort();
          const endTimes = rules.map((item) => (item.endTime === 1440 ? 0 : item.endTime)).sort();
          if (starttimes.join('') !== endTimes.join('')) {
            message.warn({ key: 'config_rules', content: '请确认规则时段是否闭合！' });
            return false;
          }
          // TODO: 确认是否使用当前接口
          const res = await addNewRules(ruleId, {
            schemeId: ruleId,
            rules,
          });
          if (res.success) {
            message.success({ key: 'config_rules', content: res.message });
            setUnvisible();
            return true;
          }
          message.error({ key: 'config_rules', content: res.message });
          return false;
        } catch (err) {
          message.warn({ key: 'config_rules', content: '请填写必填信息！' });
          return false;
        }
      }}
    >
      <span style={{ display: 'block', color: '#aaa', paddingBottom: '10px' }}>
        <i style={{ color: 'red' }}>*</i> 配置规则时间段(单位分钟)，请保证规则时间段覆盖00:00 ~
        23:59，且无交叉时间段；
        <div style={{ paddingLeft: '0.6em' }}>全天请设置(00:00 - 00:00)</div>
      </span>
      <Form
        form={form}
        autoComplete="off"
        initialValues={{
          rules: initialRules,
        }}
      >
        <Form.List name="rules">
          {(fields, { add, remove }) => (
            <>
              {fields.map((field, index) => (
                <Space key={field.key} align={'baseline'}>
                  <Form.Item
                    {...field}
                    label={`规则时段${index + 1}`}
                    name={[field.name, 'duration']}
                    rules={[{ required: true, message: '请填入规则时段' }]}
                  >
                    <TimePicker.RangePicker
                      order={false}
                      format="HH:mm"
                      placeholder={['起始时间', '结束时间']}
                    />
                  </Form.Item>

                  <Form.Item
                    {...field}
                    label="计费"
                    name={[field.name, 'price']}
                    rules={[{ required: true, message: 'Missing price' }]}
                  >
                    <Input.Group compact>
                      <Form.Item name={[field.name, 'price', 'unit']} noStyle>
                        <InputNumber
                          min={0}
                          addonBefore={'每'}
                          addonAfter={'小时'}
                          style={{ width: '50%' }}
                        />
                      </Form.Item>
                      <Form.Item name={[field.name, 'price', 'value']} noStyle>
                        <InputNumber
                          precision={2}
                          min={0}
                          placeholder="金额"
                          addonAfter={'元'}
                          style={{ width: '50%' }}
                        />
                      </Form.Item>
                    </Input.Group>
                  </Form.Item>

                  <Form.Item
                    {...field}
                    name={[field.name, 'maxPrice']}
                    rules={[{ required: true, message: '请填入时段最高收费' }]}
                  >
                    <InputNumber
                      precision={2}
                      min={0}
                      placeholder="金额"
                      addonBefore={'最高收费'}
                    />
                  </Form.Item>

                  <MinusCircleOutlined onClick={() => remove(field.name)} />
                </Space>
              ))}

              <Form.Item>
                <Button
                  type="dashed"
                  onClick={() => add({ price: { value: 0, unit: 2 } })}
                  block
                  icon={<PlusOutlined />}
                >
                  插入一个规则时段
                </Button>
              </Form.Item>
            </>
          )}
        </Form.List>
      </Form>
    </Modal>
  );
};
